const db = require("../db")
var date = require("silly-datetime");
const _ = require("lodash")

module.exports = {
    getAllRight:(req,res)=>{
        let sql =  `select * from userright`
        db.query(sql,function(err,result){
            if(err) return res.cc("获取权限失败！")
            let data = [...result]
            let temp = []
            for(let i = 0 ; i < data.length ; i++){
                if(data[i].pid == 0 ){
                    data[i].children = data.filter(item => item.pid == data[i].id)
                    temp.push(data[i])
                }
            }
            return res.send({
                code:200,
                msg:"获取权限列表成功！",
                data:temp
            })
        })
    },
    Auth2Role:(req,res)=>{
        let param = req.body
        let sql = `update role set role_right = ? where id = ?`
        db.query(sql,[param.rights,param.roleId],function(err,result){
            if(err) return res.cc(err)
            if(result.affectedRows != 1) return res.cc("分配权限失败！")
            return res.cc("分配权限成功！",200)
        })
    },
    getRightMenu:(req,res)=>{
        db.query(`select role.role_right from user,role where user.roleId = role.id and user.id = ${req.body.id}`,function(err,result){
            if(err) return res.cc(err)
            db.query(`select * from userright where userright.id in (${result[0].role_right})`,function(err,result2){
                if(err) return res.cc(err)
                let data = []
                result2.forEach(item => {
                    if(item.pid===0){
                        item.children = result2.filter(i => i.pid == item.id)
                        data.push(item)
                    }
                });
                // console.log(data);
                res.send({
                    code:200,
                    msg:"获取菜单成功！",
                    data:data
                })
            })
        })
    }

}